<?php

namespace App\Modules\Blog\Admin\Controllers;

use Illuminate\Http\Request;
use App\Modules\Blog\Models\Cate;
use App\Modules\Blog\Http\Resources\CateResource;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;
use Encore\Admin\Facades\Admin;
use Illuminate\Routing\Controller;
use App\Admin\Forms\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Form;
use Encore\Admin\Show;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Illuminate\Support\Facades\Auth;

class CateController extends Controller
{

    /**
     * Module slug
     */
    protected $mslug = "blog";
    protected $model;
    protected $title;
    protected $group = true;

    public function index(Content $content, Request $request)
    {

        $this->module = $module = get_module($this->mslug, 'app');

        $this->model = $model = new Cate();
        $this->set = $set = [
            'title'     => '日志分类',
            'set'       => true,
            'group'     => true,
            'publish'   => false    //上级目录是否允许发布内容
        ];
        return $content
            ->breadcrumb(['text' => $set['title'] . '管理'])
            ->title($set['title'] . '管理')
            ->description($module['description'])
            ->row(function (Row $row)  use ($model, $set) {
                $row->column(6, $this->treeView()->render());
                $row->column(6, function (Column $column) use ($model, $set) {    //create部分

                    $form = new \Encore\Admin\Widgets\Form($model);
                    $form->action(route('admin.blog.cate.store'));
                    //不允许生成或修改时改变parent_id,防止次序混乱
                    $form->text('title', '分类名')->rules('required');
                    $form->text('name', '标识')->rules('required');
                    if (!empty($set['group'])) {
                        $form->tags('groups', '分组');
                    }
                    if (empty($set['publish'])) {
                        $form->switch('publish', '允许发布')->default(1)->states([
                            'on'  => ['value' => 1, 'text' => '是'],
                            'off' => ['value' => 0, 'text' => '否'],
                        ]);
                    }
                    $column->append((new Box(trans('admin.new'), $form))->style('success'));
                });
            });
    }


    public function form()
    {
        $form = new Form($this->model);

        $formSet = $this->model->getFormSet();

        $onlyCreate = $this->model->getFormOnlyCreate();
        $onlyUpdate = $this->model->getFormOnlyUpdate();


        $form->display('id', 'ID');
        $form->id('title', '分类名')->rules('required');
        $form->text('title', '分类名')->rules('required');
        $form->text('name', '标识')->rules('required');
        $form->tags('groups', '分组');
        $form->switch('publish', '允许发布')->default(1)->states([
            'on'  => ['value' => 1, 'text' => '是'],
            'off' => ['value' => 0, 'text' => '否'],
        ]);


        /*


        foreach ($formSet as $field => $set) {
            if (in_array($field, $onlyCreate) && $form->isCreating()) continue;
            if (in_array($field, $onlyUpdate) && $form->isUpdateing()) continue;
            $i = 0;
            foreach ($set as $key => $value) {
                if ($i === 0) {
                    ($value === null) ? $a = $form->$key($field) : $a = $form->$key($field, $value);
                } else {
                    ($value === null) ? $a = $a->$key() : $a = $a->$key($value);
                }
                $i++;
            }
            $a;
        }*/
        /*
        $aaa = $form->display('id', 'ID');
        
        $form = $form->text('title', '分类名')->rules('required');
        $form->text('name', '标识')->rules('required');
        if (!empty($this->set['group'])) {
            $form = $form->tags('groups', '分组');
        }
        if (empty($this->set['publish'])) {
            $form->switch('publish', '允许发布')->default(1)->states([
                'on'  => ['value' => 1, 'text' => '是'],
                'off' => ['value' => 0, 'text' => '否'],
            ]);
        }*/
        return $form;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Cate();
        $rule = $model->getCreateRules();
        $message = $model->getMessages();
        $custom = $model->getComments();
        $data = $request->all();
        $validator = Validator::make(
            $data,
            $rule,
            $message,
            $custom
        );
        if ($validator->fails()) {
            //return $validator->errors()->first();
            return response()->json(['errors' => Arr::dot(Arr::dot($validator->errors()))], 422);
            //return json(['errors' => Arr::dot($validator->errors()], 422)
        }

        //忽略掉不需要保存或直接使用默认值的字段
        $this->form()->ignore($model->getIgnoreFields());
        return $this->form()->store();
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $model = new Cate();
        $data = $model->findOrFail($id);
        $result['data'] =  (new CateResource($data))->resolve();
        $result['module'] = get_module($this->mslug);
        return json_ok($result);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Content $content, $id)
    {
        return $content
            ->title('标题')
            ->description('测试')
            ->body($this->form()->edit($id));
    }


    public function update($id)
    {
        return $this->form()->update($id);
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }


    /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView()
    {
        $module = $this->module;
        $model = $this->model;
        $set = $this->set;
        $canset =  empty($this->set['set']) ? 'admin.tree.catebranch' : 'admin.tree.catebranchset';

        return $model->tree(function (Tree $tree) use ($canset) {
            $tree->setView([
                'tree'   => 'admin::tree',
                'branch' => $canset,
            ]);
            $tree->disableCreate();
            $tree->branch(function ($branch) {
                $payload = "&nbsp;<strong>{$branch['title']}</strong> -- {$branch['name']}";
                return $payload;
            });
        });
    }
}
